<template>
    <div class="planList-index yuan-container">
        <div class="filter-panel">
            <span class="planList-title">
                {{planSimulation.planName}}
            </span>
            <div class="filter-list">
                <span class="filter-tips ">饮片库存数量：
                    <span class="font-bignum c-primary">{{ ypTotal }}</span>
                    <span>kg</span>
                </span>
            </div>

        </div>
        <div class="planList-top filter-panel">
            <div class="filter-list">
                <span class="filter-tips">实际生产饮片数量：
                    <a-input class="filter-input" suffix="kg" v-model="pageData.prodNum" @input="prodNumChange"></a-input>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips ">药材需求量：
                    <span class="font-bignum c-primary">{{(pageData.needNum  )|| '--' }}</span>
                    <span>kg</span>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">实际投料量:
                    <span class="font-bignum c-warning">{{(pageData.touliao  )|| '--'}}</span>
                    <span>kg</span>
                </span>
            </div>
        </div>
        <div class="planList-top filter-panel">
            <div class="filter-list">
                <span class="filter-tips">计划投料批量：<span class="mast-ico"></span></span>
                <a-select v-model="pageData.inputP" allowClear placeholder="计划投料批量">
                    <a-select-option :value="item.value" v-for="item in inputBatchList" :key="item.value">{{item.value}}</a-select-option>
                </a-select>
                <span> kg/批</span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">计划投料批次：</span>
                <span class="font-bignum c-primary">{{(pageData.touliao/pageData.inputP  ) || 0 | toDecimalNoZero}}</span>
                <span>批</span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">实际投料批量：</span>
                    <a-input v-model="pageData.actualP"></a-input>
                <span> kg/批</span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">实际投料批次：</span>
                <span class="font-bignum c-primary">{{(pageData.touliao/pageData.actualP  ) || 0 | toDecimalNoZero}}</span>
                <span>批</span>
            </div>
        </div>
        
        <div class="planList-top filter-panel">
            <div class="filter-list">
                <span class="filter-tips">预计产出时间：
                    <span class="mast-ico"></span>
                    <a-date-picker class="yuan-form-input" @change="planTimeChange($event)" placeholder="预计产出时间" v-model="pageData.planTime" valueFormat="YYYY-MM-DD" />
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">完成天数：
                    <span class="mast-ico"></span>
                    <a-input-number class="yuan-form-input" @change="finishDayChange($event)" placeholder="完成天数" v-model="pageData.finishDay"/>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">预计完成时间：<span class="mast-ico"></span></span>
                <a-date-picker class="yuan-form-input" placeholder="预计完成时间" v-model="pageData.finishTime" valueFormat="YYYY-MM-DD" :disabled="true" />
            </div>

            <div class="filter-list">
                <span class="filter-tips">前处理工艺流程：</span>
                <a-select v-model="pageData.tech" placeholder="工艺流程">
                    <a-select-option :value="item.value" v-for="item in techList" :key="item.value">{{item.value}}</a-select-option>
                </a-select>
            </div>
            <div class="filter-list">
                <span class="filter-tips">工艺注意事项：</span>
                <a-input v-model="pageData.techNotice" placeholder="工艺注意事项"></a-input>
            </div>
        </div>
        <a-tag>提示:计划投料批量、前处理工艺流程请在系统设置-产品管理-提取饮片配置</a-tag>
        <div style="border-bottom:solid 1px #999;margin:20px 0"></div>
        <!-- <div style="font-size:16px;font-weight:bold;margin-bottom:10px">
            辅料
        </div>
        <div class="filter-panel">
            <div v-for="(item,idx) in accSelList">
                <div class="filter-list">
                    <span class="filter-tips">投入辅料：</span>
                    <a-select v-model="accSelList[idx].accId" allowClear placeholder="请选择辅料">
                        <a-select-option :value="item.id" v-for="item in accList">{{item.materialName}}</a-select-option>
                    </a-select>
                </div>
                <div class="filter-list">
                    <span class="filter-tips">投入数量：</span>
                    <a-input class="filter-input" suffix="kg" v-model="accSelList[idx].inputNum"></a-input>
                </div>
                <div class="filter-list" v-if="idx===0">
                    <a-button type="primary" @click="addAcc">新增</a-button>
                </div>
                <div class="filter-list" v-if="idx!==0">
                    <a-button type="danger" @click="removeAcc(idx)">删除</a-button>
                </div>
            </div>
        </div> -->

        <div class="filter-panel" style="display:flex;align-items: center;margin-bottom:20px">
            <div class="filter-list">
                <span class="filter-tips" style="font-size:16px;font-weight:bold;">
                    {{planSimulation.materialName}}{{planSimulation.materialType}} 库存现状
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips ">药材总库存：
                    <span class="font-bignum c-primary">{{stockTotal |toDecimalNoZero }}</span>
                    <span>kg</span>
                </span>
            </div>
        </div>
        <template>
            <div class="filter-panel">
                <div class="filter-list">
                    <span>批号：</span>
                    <a-input-search allowClear v-model="pageParams.batch" placeholder="请输入批号" @search="resetList" />
                </div>
                <!-- <div class="filter-list">
                    <span>可供销售天数：</span>
                    <span class="filter-range">
                        <a-input v-model="pageParams.sellDayStart"></a-input>
                        <span class="filter-tips">~</span>
                        <a-input v-model="pageParams.sellDayEnd"></a-input>
                        <span class="filter-tips">天</span>
                    </span>
                </div>
                <div class="filter-list">
                    <span>质量状态：</span>
                    <a-select v-model="pageParams.qualityState" @change="resetList" allowClear placeholder="请选择质量状态">
                        <a-select-option value="1">合格</a-select-option>
                        <a-select-option value="2">不合格</a-select-option>
                    </a-select>
                </div>
                <div class="filter-list">
                    <span>有效期：</span>
                    <a-range-picker :mode="['month','month']" :open="monthPickShow" @panelChange="handlePanelChange"
                        v-model="billMonth" @openChange="handleOpenChange" :placeholder="['开始日期','结束日期']"
                        :format="['YYYY-MM','YYYY-MM']" />
                </div> -->
                <div class="filter-list">
                    <a-button type="primary" @click="getList" class="filter-list">搜索</a-button>
                </div>
            </div>
            <div class="table">
                <a-checkbox-group v-model="tableSelect" @change="pageListSelectChange" style="width:100%">
                    <a-table bordered :rowKey="(row)=>row.id" :data-source="pageList" :columns="packageColumns"
                        :pagination="false" :loading="loading">
                        <template slot="select" slot-scope="text, record, index">
                            <a-checkbox :value="index" :defaultChecked="record.isSelect"></a-checkbox>
                        </template>
                        <template slot="inputNumber" slot-scope="text, record, index">
                            <span v-if="!pageList[index].isSelect">--</span>
                            <a-input type="number" style="width:100px" placeholder="请输入数量"
                                v-model="pageList[index]['inputNumber']" @input="inputNumChange" v-else />

                        </template>
                        
                    </a-table>
                </a-checkbox-group>
            </div>
        </template>

    </div>
</template>
<script lang="ts">
import nextApi from "@/api/nextApi";
import warningApi from "@/api/warningApi";
import { toDecimalNoZero } from "@/utils";
import { Vue, Component, Prop, Watch } from "vue-property-decorator";

@Component({
    name: "dom",
    components: {},
})
export default class index extends Vue {
    @Prop({ default: "" }) planSimulation!: any;
    @Prop({ default: "" }) pageDetail!: any;
    // 计划表格
    packageColumns = [
        {
            align: "center",
            dataIndex: "select",
            key: "select",
            title: "",
            scopedSlots: { customRender: "select" },
        },
        {
            align: "center",
            dataIndex: "inNo",
            key: "inNo",
            title: "批号",
        },
        {
            align: "center",
            dataIndex: "inDate",
            key: "inDate",
            title: "生产日期",
        },
        {
            align: "center",
            dataIndex: "recheckDate",
            key: "recheckDate",
            title: "复验期",
        },
        {
            align: "center",
            dataIndex: "quantityStorage",
            key: "quantityStorage",
            title: "库存数量",
            // customRender: (text: string, record: any, index: number) => toDecimalNoZero(record.surplus, 2),
        },

        {
            align: "center",
            dataIndex: "state",
            key: "state",
            title: "状态",
        },
        {
            align: "center",
            dataIndex: "inputNumber",
            key: "inputNumber",
            title: "投料量（kg）",
            scopedSlots: { customRender: "inputNumber" },
        },
        {
            align: "center",
            dataIndex: "recordWeight",
            key: "recordWeight",
            title: "记录数量",
        },
    ];
    loading = false;
    pageParams: any = {
        batch: "",
        qualityState: undefined,
        sellDayStart: "",
        sellDayEnd: "",
        startTime: "",
        endTime: "",
    };
    pagination = {
        pageSize: 999,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    pageList: any[] = [];
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }
    stockTotal = 0;
    async getList() {
        this.tableSelect = [];
        this.pageList = [];
        try {
            this.loading = true;
            const res = await nextApi.getZYCStorage({
                // ...this.pageParams,
                name:this.pageDetail.materialName,
                pageSize: this.pagination.pageSize,
                page: this.pagination.current,
                // materialName: this.planSimulation.materialName,
                // materialType: this.planSimulation.materialType,
            });
            // this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.list || [];
            // let stockTotal = 0;
            // this.pageList.forEach((item) => {
            //     stockTotal += Number(item.surplus || 0);
            // });
            this.stockTotal = res.data?.total;
            // 还原以前的投料信息
            const alarm = this.pageDetail;
            if (alarm.processPlanInputNewList.length > 0) {
                alarm.processPlanInputNewList.forEach((listOne) => {
                    this.pageList.forEach((item, idx) => {
                        if (item.id === listOne.stockId) {
                            item.isSelect = true;
                            item["inputNumber"] = listOne.inputNum;
                            this.tableSelect.push(idx);
                        }
                    });
                });
                this.inputNumChange();
            }
            if(this.pageList.length == 0){
                this.$message.warning('该品种中药材暂无库存，请在原药材库存表添加库存信息')
            }
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    techList = [];
    inputBatchList = [];
    async getMaterInfo() {
        const res = await warningApi.getMaterialBreed(this.pageDetail.prodId);
        const data = res.data;
        this.inputBatchList = JSON.parse(data.inputBatch || "") || [];
        this.pageData.techNotice = data.notice;
        this.techList = JSON.parse(data.tech || "") || [];
    }
    billMonth = [];
    monthPickShow = false;
    handlePanelChange(value, mode) {
        if (mode[1] === "date") {
            const arr = value.map((item) => item.format("YYYY-MM"));
            this.billMonth = arr;
            this.pageParams.startTime = arr[0];
            this.pageParams.endTime = arr[1];
            this.resetList();
            this.monthPickShow = false;
        }
    }
    handleOpenChange(status) {
        if (status) {
            this.monthPickShow = true;
        } else {
            this.monthPickShow = false;
        }
    }

    tableSelect: number[] = [];
    pageListSelectChange() {
        console.info(this.tableSelect);
        let pageList = [...this.pageList];
        pageList = pageList.map((item, index) => {
            return {
                ...item,
                isSelect: this.tableSelect.indexOf(index) >= 0 ? true : false,
            };
        });

        this.pageList = pageList;
        this.inputNumChange();
        console.log( this.pageList);
        
    }
    async mounted() {
        await this.getMaterInfo();
        this.pageData = {
            touliao: "",
            prodNum: this.pageDetail.prodNum,
            needNum: this.pageDetail.needNum,
            planTime: this.pageDetail.planTime || '',
            finishDay: this.pageDetail.finishDay || '',
            finishTime: this.pageDetail.finishTime || '',
            tech: this.pageDetail.tech ? this.pageDetail.tech : undefined,
            techNotice: this.pageDetail.techNotice ? this.pageDetail.techNotice : this.pageData.techNotice,
            inputP: this.pageDetail.inputP ? this.pageDetail.inputP : undefined,
            actualP: this.pageDetail.actualP ? this.pageDetail.actualP : undefined,
        };
        this.getNeedNum();
        this.getList();
        this.getAccList();
        this.getTotalPelletStorage()
    }
    ypTotal = 0
    async getTotalPelletStorage(){
        let params = {
            name:this.pageDetail.prodName,
            standard:this.pageDetail.standard,
            type:'饮片'
        }
        const res = await nextApi.getStorageOfhalfRaw(params)
        let data = res?.data || {}
        this.ypTotal = data.ypStockNum
    }
    pageData: any = {
        touliao: "",
        prodNum: "",
        needNum: "",
        tech: "",
        techNotice: "",
    };
    simulationTimer: number | null = null;
    inputNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        if (this.tableSelect.length === 0) return;
        this.simulationTimer = setTimeout(async () => {
            let total = 0;
            this.pageList.forEach((item) => {
                if (Number(item.inputNumber) > item.surplus && item.isSelect === true) {
                    this.$message.error("投料数量不能大于库存量");
                    return;
                }
                if (item.isSelect === true) {
                    total += Number(item.inputNumber) || 0;
                }
            });
            this.pageData.touliao = toDecimalNoZero(total);
        }, 500);
    }
    prodNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            this.getNeedNum();
        }, 500);
    }
    async getNeedNum() {
        try {
            this.loading = true;
            const res = await warningApi.getNeedNum({
                id: this.pageDetail.prodId,
                need: this.pageData.prodNum,
            });
            this.pageData.needNum = res.data;
        } finally {
            this.loading = false;
        }
    }

    accSelList: any[] = [{ inputNum: "", accId: "" }];
    accList: any[] = [];
    async getAccList() {
        this.accList = [];
        try {
            this.loading = true;
            const res = await warningApi.materialStockList({
                pageSize: 999,
                page: 1,
                materialType: "辅料",
            });
            this.accList = res.data?.records || [];

            // 还原以前的投料信息
            const alarm = this.pageDetail;
            if (alarm?.processPlanInputList?.length > 0) {
                let accSelList: any[] = [];
                alarm.processPlanInputList.forEach((listOne) => {
                    this.accList.forEach((item, idx) => {
                        if (item.id === listOne.materialId) {
                            listOne.accId = item.id;
                            accSelList.push(listOne);
                        }
                    });
                });
                if (accSelList.length === 0) accSelList = [{}];
                this.accSelList = JSON.parse(JSON.stringify(accSelList));
                this.inputNumChange();
            }
        } finally {
            this.loading = false;
        }
    }
    addAcc() {
        this.accSelList.push({});
    }
    removeAcc(idx) {
        this.accSelList.splice(idx, 1);
    }

    planTimeChange(v) {
        if(v){
            let time = new Date(v).getTime()
            if(this.pageData.finishDay){
                let oneDayTimeStamp = 24*60*60*1000
                let finishTimeStamp = time + (this.pageData.finishDay*oneDayTimeStamp)
                this.pageData.finishTime = new Date(finishTimeStamp).toLocaleDateString()
            }
        }
    }
    finishDayChange(v){
        if(v){
            if(this.pageData.planTime){
                let planTimeStamp = new Date(this.pageData.planTime).getTime()
                let oneDayTimeStamp = 24*60*60*1000
                let finishTimeStamp = planTimeStamp + (v*oneDayTimeStamp)
                this.pageData.finishTime = new Date(finishTimeStamp).toLocaleDateString()
            }
        }
    }

    getPageInfo() {
        console.log(this.pageData);
        
        if (!this.pageData.finishTime) {
            this.$message.error("请选择制剂计划预计完成时间");
            return false;
        }
        if (!this.pageData.inputP) {
            this.$message.error("请选择提取计划投料批量");
            return false;
        }
        const processPlanInputList: any[] = [];
        let total = 0;
        let isHave = false;
        this.pageList.forEach((item) => {
            if (Number(item.inputNumber) > item.surplus) {
                this.$message.error("提取计划投料数量不能大于库存量");
                return;
            }
            if (item.isSelect === true) {
                isHave = true;
                total += Number(item.inputNumber) || 0;
                processPlanInputList.push({
                    isPro: true,
                    stockId: item.id,
                    batch: item.inNo,
                    type:'中药材',
                    productDate:item.inDate,
                    recheckDate:item.recheckDate,
                    qualityState:item.state,
                    storageNum:item.quantityStorage,
                    inputNum: item.inputNumber,
                    inputName:item.name,
                    materialName: item.materialName,
                    materialType: item.materialType,
                    materialId: item.materialId,
                });
            }
        });
        if (!isHave) {
            this.$message.error("提取计划还没有选择投料");
            return false;
        }
        // 辅料
        this.accSelList.forEach((item) => {
            if (item.inputNum > 0) {
                const findOne = this.accList.find((one) => {
                    return one.id === item.accId;
                });
                if (findOne) {
                    processPlanInputList.push({
                        inputNum: item.inputNum,
                        materialName: findOne.materialName,
                        materialType: findOne.materialType,
                        materialId: findOne.id,
                    });
                }
            }
        });
        return [
            {
                ...this.pageDetail,
                isPro: true,
                processPlanInputNewList:processPlanInputList,
                finishTime: this.pageData.finishTime,
                planTime: this.pageData.planTime,
                finishDay: this.pageData.finishDay,
                needNum: this.pageData.needNum,
                prodNum: this.pageData.prodNum,
                inputNum: total,
                inputP: this.pageData.inputP,
                actualP:this.pageData.actualP,
                inputPc:this.pageData.touliao/this.pageData.inputP,
                actualBatch:this.pageData.touliao/this.pageData.actualP,
                tech: this.pageData.tech,
                techNotice: this.pageData.techNotice,
            },
        ];
    }
}
</script>
<style lang="scss">
.planList-index {
    .planList-top {
        font-size: 16px;
        padding-bottom: 10px;
    }
    .planList-title {
        font-weight: bold;
        font-size: 20px;
    }

    .overview-panel {
        background-color: #fff;
        padding: 10px 10px;
    }
    .overview-title {
        margin-right: 30px;
    }
    .overview-titlebox {
        padding: 10px 0;
    }
}
</style>
